<template>
  <div class="commonBg mx-auto bg-[#ffffff] p-[80px_40px]">
    <div class="mx-auto max-w-[1720px]">
      <h2 class="color-gray-333 !mb-[30px] text-[20px] font-[600]">用户管理</h2>

      <!-- 搜索表单 -->
      <a-form
        layout="inline"
        :model="searchParams"
        @finish="doSearch"
      >
        <a-form-item label="ID">
          <a-input
            v-model:value="searchParams.id"
            placeholder="输入ID"
          />
        </a-form-item>
        <a-form-item label="账号">
          <a-input
            v-model:value="searchParams.userAccount"
            placeholder="输入账号"
          />
        </a-form-item>
        <a-form-item label="用户名">
          <a-input
            v-model:value="searchParams.userName"
            placeholder="输入用户名"
          />
        </a-form-item>
        <a-form-item label="用户角色">
          <a-select
            v-model:value="searchParams.userRole"
            placeholder="选择用户角色"
            class="!w-[150px]"
            :options="UserRoleOptions"
          >
          </a-select>
        </a-form-item>
        <a-form-item class="!mr-0 !ml-auto">
          <a-button
            type="primary"
            html-type="submit"
            >搜索</a-button
          >
        </a-form-item>
      </a-form>
      <a-divider />

      <!-- 表格 -->
      <a-table
        :columns="columns"
        :data-source="data"
        :pagination="pagination"
        @change="doTableChange"
      >
        <template #headerCell="{ column }">
          <template v-if="column.key === 'name'">
            <span>
              <smile-outlined />
              Name
            </span>
          </template>
        </template>

        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'userAvatar'">
            <a-avatar
              :src="record.userAvatar"
              :size="34"
              shape="square"
              class="!bg-[#fafafa]"
            />
          </template>
          <template v-else-if="column.dataIndex === 'userRole'">
            <div v-if="record.userRole === UserRole.ADMIN">
              <a-tag color="green">管理员</a-tag>
            </div>
            <div v-else>
              <a-tag color="blue">普通用户</a-tag>
            </div>
          </template>
          <template v-else-if="column.dataIndex === 'createTime'">
            {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm') }}
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button
                type="primary"
                size="small"
                class="!text-[12px]"
                @click="handleEditUser(record)"
                >编辑</a-button
              >
              <a-popconfirm
                title="删除后不可恢复！"
                ok-text="删除"
                cancel-text="取消"
                @confirm="doDelete(record.id)"
              >
                <a-button
                  danger
                  size="small"
                  class="!text-[12px]"
                  v-if="record.userRole !== 'admin'"
                  >删除</a-button
                >
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { SmileOutlined } from '@ant-design/icons-vue';
import { listUserVoByPage, deleteUser } from '@/api/userController';
import { message } from 'ant-design-vue';
import dayjs from 'dayjs';
import { UserRole, UserRoleOptions } from '@/constants/role.enum';
import { eventBus, EventNames } from '@/utils/eventBus';

// 数据
const data = ref<API.UserVO[]>([]);
const total = ref<number>(0);

// 注入全局用户信息弹窗方法
const showUserInfoModal = inject<(userData?: API.UserVO) => void>('showUserInfoModal');

// 字段列表
const columns = [
  {
    title: 'id',
    dataIndex: 'id'
  },
  {
    title: '账号',
    dataIndex: 'userAccount'
  },
  {
    title: '用户名',
    dataIndex: 'userName'
  },
  {
    title: '头像',
    dataIndex: 'userAvatar'
  },
  {
    title: '简介',
    dataIndex: 'userProfile'
  },
  {
    title: '用户角色',
    dataIndex: 'userRole'
  },
  {
    title: '创建时间',
    dataIndex: 'createTime'
  },
  {
    title: '操作',
    key: 'action'
  }
];

// 搜索条件
const searchParams = reactive<API.UserQueryRequest>({
  // 页码
  pageNum: 1,
  // 每页条数
  pageSize: 10,
  // 账号
  userAccount: '',
  // 用户名
  userName: ''
});

// 分页参数
const pagination = computed(() => {
  return {
    // 当前页码
    current: searchParams.pageNum ?? 1,
    // 每页条数
    pageSize: searchParams.pageSize ?? 10,
    // 总条数
    total: total.value,
    // 是否显示分页器
    showSizeChanger: true,
    // 显示总条数
    showTotal: (total: number) => `共 ${total} 条`
  };
});

/**
 * 表格变化处理
 * @param page 分页参数
 */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const doTableChange = (page: any) => {
  searchParams.pageNum = page.current;
  searchParams.pageSize = page.pageSize;
  fetchData();
};

/**
 * 搜索数据
 */
const doSearch = () => {
  searchParams.pageNum = 1;
  fetchData();
};

/**
 * 编辑用户
 */
const handleEditUser = (record: API.UserVO) => {
  if (showUserInfoModal) {
    showUserInfoModal(record);
  }
};

/**
 * 删除数据
 */
const doDelete = async (id: number) => {
  try {
    const res = await deleteUser({ id: id as number });
    if (res.data?.code === 0) {
      message.success('删除成功');
      fetchData();
    } else {
      message.error(res.data?.message ?? '删除失败');
    }
  } catch (error) {
    console.error(error);
  }
};

/**
 * 获取数据
 */
const fetchData = async () => {
  try {
    const res = await listUserVoByPage(searchParams);
    if (res.data?.code === 0 && res.data.data) {
      data.value = res.data.data.records as API.UserVO[];
      // 确保 total 是数字类型
      total.value = Number(res.data.data.totalRow) || 0;
    }
  } catch (error) {
    console.error(error);
    message.error('获取数据失败');
  }
};

/**
 * 处理用户更新成功事件
 */
const handleUserUpdateSuccess = () => {
  console.log('收到用户更新成功事件，刷新表格');
  fetchData();
};

/**
 * 初始化
 */
onMounted(() => {
  fetchData();

  // 监听用户更新成功事件，自动刷新表格
  eventBus.on(EventNames.USER_UPDATE_SUCCESS, handleUserUpdateSuccess);
});

// 组件卸载时移除事件监听
onUnmounted(() => {
  eventBus.off(EventNames.USER_UPDATE_SUCCESS, handleUserUpdateSuccess);
});
</script>

<style scoped>
::v-deep(.ant-pagination) {
  justify-content: center;
}
</style>
